package com.example.proxy;

import com.example.dto.RefreshBean;
import com.example.dto.RefreshField;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Field;

/****
 *
 * 定义代理对象，替代可能需要刷新的属性的。
 */
public class DefaultProxyBean implements MethodInterceptor {

    Logger logger = LoggerFactory.getLogger(getClass());

    private RefreshBean refreshBean;

    private ApplicationContext applicationContext;

    public DefaultProxyBean(RefreshBean refreshBean, ApplicationContext applicationContext) {
        this.refreshBean = refreshBean;
        this.applicationContext = applicationContext;
    }

    @Override
    public Object intercept(Object obj, java.lang.reflect.Method method, Object[] args, MethodProxy proxy) throws Throwable {
        return method.invoke(refreshBean.getBeanVal(), args);
    }

    public RefreshBean getRefreshBean() {
        return refreshBean;
    }

    public void setRefreshBean(RefreshBean refreshBean) {
        this.refreshBean = refreshBean;
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /****
     * 刷新bean的属性值
     * @param appKey
     * @param appVal
     * @throws Exception
     */
    public void refreshBeanProp(String appKey, Object appVal) throws Exception {
        for (RefreshField refreshField : refreshBean.getFields()) {
            if (refreshField.getFieldKey().equalsIgnoreCase(appKey)) {
                Object beanVal = refreshBean.getBeanVal();
                Field field = refreshField.getField();
                field.setAccessible(true);
                field.set(beanVal, appVal);
            }
        }
    }
}
